package com.tianxia120.website.admin.controller;

import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.tianxia120.website.admin.service.LoginService;
import com.tianxia120.website.bean.model.User;
import com.tianxia120.website.data.controller.BaseController;
import com.tianxia120.website.data.entity.Result;
import com.tianxia120.website.data.interceptors.Get;
import com.tianxia120.website.data.interceptors.Post;
import com.tianxia120.website.data.utils.FieldUtils;
import com.tianxia120.website.data.validator.LoginValidator;

/**
 * @createTime: 2018/9/21 13:02
 * @author: HingLo
 * @description: 登录相关操作
 */
public class LoginController extends BaseController {

    @Inject
    private LoginService loginService;

    /**
     * 登录操作
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     */
    @Before({LoginValidator.class, Post.class})
    public void login(String username, String password, String code) {
        if (validateCaptcha(code)) {
            error("验证码错误");
        }
        Result result = loginService.login(username, password);
        // 登录成功后将数据放到session中
        User user = (User) result.getData();
        setSessionAttr(FieldUtils.LOGIN, user);
        renderJson(result);
    }

    /***
     * 请求验证码
     */
    @Before(Get.class)
    public void code() {
        renderCaptcha();
    }

}
